package com.example.pinnedheaderlistviewdemo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.example.pinnedheaderlistviewdemo.R;
public class BladeView extends View {
    private OnItemClickListener mOnItemClickListener;
    String[] mChars = {"#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
            "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
            "Y", "Z"};
    int choose = -1;
    Paint paint = new Paint();
    boolean showBkg = false;
    private PopupWindow mPopupWindow;
    private TextView mPopupText;
    private Handler handler = new Handler();
    private int columns = 1;//列数
    private float chooseTextSize;
    private float defaultTextSize;
    private int defaultTextColor;
    private int chooseTextColor;
    private boolean chooseBold;
    private int touchBackgroundColor;
    private boolean showBackgroundcolor;
    public BladeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = getContext(context).obtainStyledAttributes(attrs, R.styleable.bladeView);//TypedArray是一个数组容器
        defaultTextSize = a.getDimension(R.styleable.bladeView_defaultTextSize, getResources().getDimensionPixelSize(R.dimen.bladeview_fontsize));
        chooseTextSize = a.getDimension(R.styleable.bladeView_chooseTextSize, getResources().getDimensionPixelSize(R.dimen.bladeview_fontsize));
        defaultTextColor = a.getColor(R.styleable.bladeView_defaultTextColor, Color.parseColor("#141414"));
        chooseTextColor = a.getColor(R.styleable.bladeView_chooseTextColor, Color.parseColor("#CD0000"));
        touchBackgroundColor = a.getColor(R.styleable.bladeView_touchBackgroundColor, Color.parseColor("#FFFFFF"));
        columns= a.getInt(R.styleable.bladeView_column, 1);
        chooseBold = a.getBoolean(R.styleable.bladeView_chooseBold, false);
        showBackgroundcolor = a.getBoolean(R.styleable.bladeView_touchShowBackgroundColor, true);
        a.recycle();
    }
    public BladeView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
    private Context getContext(Context context) {
        return context;
    }
    public BladeView(Context context) {
        super(context);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (showBkg) {
            if (showBackgroundcolor){
                canvas.drawColor(touchBackgroundColor);
            }
        }
        for (int i = 0; i < mChars.length; i++) {
            paint.setColor(defaultTextColor);//默认字体
            paint.setTextSize(defaultTextSize);
            paint.setFakeBoldText(true);
            paint.setAntiAlias(true);
            if (i == choose) {
                paint.setColor(chooseTextColor);
                paint.setTextSize(chooseTextSize);
                if (chooseBold){
                    paint.setTypeface(Typeface.DEFAULT_BOLD);	//加粗
                }
            }
            int height = getHeight();//控件高度
            int width = getWidth();//控件
            int lines = (int) Math.ceil(mChars.length*1.0 / columns);//根据需要展示总数/列数就是行数
            float singleLineHight = (float) (height *1.0/ lines);//每一行高度
            Log.i("11111", "onDraw: "+singleLineHight);
            int singleCharWith = width / columns;
            //绘制位置charWith*i是每个开始位置+charWith / 2是每个字位于下个的位置中间+ paint.measureText(b[i]) / 2字的宽度居中
            int currentLine = 0;
            int alreadLine=0;//已经画好的行数量
            if (i < columns) {//求当前所在行数
                currentLine =(int)Math.floor( i*1.0 / columns);
            }else{
                currentLine =(int)Math.ceil( i*1.0 / columns);
                if (i%columns==0){
                    currentLine++;
                }
            }
            if (currentLine>0){//如果是第一行的话0就是-l这样不可以
                alreadLine = --currentLine;
            }
            int xp=i%columns;
            float xPos = singleCharWith * xp + singleCharWith / 2 - paint.measureText(mChars[i]) / 2;
            //alreadLine * singleLineHight已经画好了的总高度  singleLineHight当前高度    字体在高度中间((singleLineHight- paint.measureText(b[i]))/2)
            float yPos = alreadLine * singleLineHight + singleLineHight-((singleLineHight- paint.measureText(mChars[i]))/2- paint.measureText(mChars[i])/2);
            canvas.drawText(mChars[i], xPos, yPos, paint);
            paint.reset();
        }
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();//当前触摸点
        Log.i("333", "dispatchTouchEvent: "+y);
        final float x = event.getX();//当前触摸点
        final int oldChoose = choose;
        final int touchLine   = (int) (y / getHeight()*mChars.length/columns);//当前触摸行
        final int touchColumn = (int) Math.ceil (x / getWidth()*columns);//当前触摸列
        final int c  =touchLine*columns+touchColumn-1;//当前触摸字母
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                showBkg = true;
                if (oldChoose != c) {
                    if (c >= 0 && c < mChars.length) {    //让第一个字母响应点击事件
                        performItemClicked(c);
                        choose = c;
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (oldChoose != c) {
                    if (c >= 0 && c < mChars.length) {    //让第一个字母响应点击事件
                        performItemClicked(c);
                        choose = c;
                        invalidate();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                showBkg = false;
                choose = -1;
                dismissPopup();
                invalidate();
                break;
        }
        return true;
    }
    public void setColumns(int columns) {
        this.columns = columns;
        postInvalidate();
    }
    public void setChooseTextColor(int chooseTextColor) {
        this.chooseTextColor = chooseTextColor;
    }
    public void setDefaultTextColor(int defaultTextColor) {
        this.defaultTextColor = defaultTextColor;
        postInvalidate();
    }
    public void setDefaultTextSize(float defaultTextSize) {
        this.defaultTextSize = defaultTextSize;
        postInvalidate();
    }
    public void setChooseTextSize(float chooseTextSize) {
        this.chooseTextSize = chooseTextSize;
    }

    public void setShowBackgroundcolor(boolean showBackgroundcolor) {
        this.showBackgroundcolor = showBackgroundcolor;
    }

    public void setTouchBackgroundColor(int touchBackgroundColor) {
        this.touchBackgroundColor = touchBackgroundColor;
        showBackgroundcolor=true;
    }
    public void setChooseBold(boolean chooseBold) {
        this.chooseBold = chooseBold;
    }

    private void showPopup(int item) {
        if (mPopupWindow == null) {
            handler.removeCallbacks(dismissRunnable);
            mPopupText = new TextView(getContext());
            mPopupText.setBackgroundColor(Color.GRAY);
            mPopupText.setTextColor(Color.WHITE);
            mPopupText.setTextSize(getResources().getDimensionPixelSize(R.dimen.bladeview_popup_fontsize));
            mPopupText.setGravity(Gravity.CENTER_HORIZONTAL
                    | Gravity.CENTER_VERTICAL);

            int height = getResources().getDimensionPixelSize(R.dimen.bladeview_popup_height);

            mPopupWindow = new PopupWindow(mPopupText, height, height);
        }

        String text = "";
        if (item == 0) {
            text = "#";
        } else {
            text = Character.toString((char) ('A' + item - 1));
        }
        mPopupText.setText(text);
        if (mPopupWindow.isShowing()) {
            mPopupWindow.update();
        } else {
            mPopupWindow.showAtLocation(getRootView(),Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        }
    }

    private void dismissPopup() {
        handler.postDelayed(dismissRunnable, 800);
    }
    Runnable dismissRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mPopupWindow != null) {
                mPopupWindow.dismiss();
            }
        }
    };


    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    private void performItemClicked(int item) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(mChars[item]);
            showPopup(item);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(String s);
    }

}
